﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace mSpy.UI.Model
{
    public class SavedConnection
    {
        public string ServerName { get; set; }
        public DeploymentType DeploymentType { get; set; }
        public string Domain { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        public string Organization { get; set; }

        public void Save(string filePath)
        {
            List<SavedConnection> save = new List<SavedConnection>();

            var connections = SavedConnection.GetSaved(filePath);
            if (!connections.Any(c =>
                        c.ServerName.Equals(this.ServerName, StringComparison.InvariantCultureIgnoreCase) &&
                        c.Organization.Equals(this.Organization, StringComparison.InvariantCultureIgnoreCase)))
            {
                save.Add(this);
            }

            connections.ForEach(c =>
            {
                if (c.ServerName.Equals(this.ServerName, StringComparison.InvariantCultureIgnoreCase) &&
                c.Organization.Equals(this.Organization, StringComparison.InvariantCultureIgnoreCase))
                {
                    save.Add(this);
                }
                else
                {
                    save.Add(c);
                }
            });

            XmlSerializer xs = new XmlSerializer(typeof(List<SavedConnection>));
            try
            {
                using (StreamWriter sw = new StreamWriter(filePath))
                {
                    xs.Serialize(sw, save);
                }
            }
            catch { }
        }

        public static List<SavedConnection> GetSaved(string filePath)
        {
            List<SavedConnection> connections = new List<SavedConnection>();

            if (File.Exists(filePath))
            {
                try
                {
                    XmlSerializer xs = new XmlSerializer(typeof(List<SavedConnection>));
                    using (FileStream fs = File.Open(filePath, FileMode.Open))
                    {
                        connections = xs.Deserialize(fs) as List<SavedConnection>;
                    }
                }
                catch { }
            }

            return connections;
        }
    }
}
